<template>
  <div class="app-container">
    <div class="serach-container">
      <div class="search-inputs">
        <el-form :inline="true" :model="simpleForm" class="demo-form-inline searchCondition" label-position="right" label-width="100px">
          <el-form-item label="白名单名称">
            <el-input v-model="simpleForm.whitelistName" placeholder="请输入白名单名称" />
          </el-form-item>
          <el-form-item label="白名单对象">
            <el-select v-model="simpleForm.dealerName" clearable filterable placeholder="请选择白名单对象">
              <el-option v-for="(item, index) in dealerOptions" :key="index + '_'+ item.dealerCode" :label="item.dealerName" :value="item.dealerName" />
            </el-select>
          </el-form-item>
          <el-form-item label="白名单城市">
            <el-select v-model="simpleForm.city" clearable filterable placeholder="请选择白名单城市">
              <el-option v-for="(item, index) in cityOptions" :key="index + '_'+ item.cityCode" :label="item.cityName" :value="item.cityName" />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="queryTableList">查询</el-button>
          <el-button @click="handelRest">重置</el-button>
        </el-form>
      </div>
    </div>
    <div class="section-container">
      <el-table v-loading="listLoading" size="mini" :data="tables.data" border fit highlight-current-row style="width: 100%" height="600">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column v-for="item in tables.columns" :key="item.key" :label="item.lable" :align="item.align" :width="item.width">
          <template slot-scope="{row}">
            <div v-if="item.key === 'status'">
              <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="toggleStatus(row)" />
            </div>
            <div v-else-if="item.key === 'dealerList'">
              <div v-if="row.dealerListStr.length > 20">
               <el-popover placement="top-start" title="" max-width="800" trigger="hover" popper-class="workorder-problem-desc">
                  <div>{{ row.dealerListStr }}</div>
                  <span slot="reference">
                    {{ row.dealerListStr.substr(0,20) + '...' }}
                  </span>
                </el-popover>
                </div>
               <div v-else>{{ row.dealerListStr }}</div>
            </div>
            <div v-else-if="item.key === 'cityList'">
               <!-- <div>{{ row.cityList | listFomat }}</div> -->
               <div v-if="row.cityListStr.length > 20">
               <el-popover placement="top-start" title="" max-width="800" trigger="hover" popper-class="workorder-problem-desc">
                  <div>{{ row.cityListStr }}</div>
                  <span slot="reference">
                    {{ row.cityListStr.substr(0,20) + '...' }}
                  </span>
                </el-popover>
                </div>
               <div v-else>{{ row.cityListStr }}</div>
            </div>
            <span v-else-if="item.key === 'endTime'">{{ row | effectiveEndTimeFilter }}</span>
            <span v-else>{{ row[item.key] }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180" fixed="right">
          <template slot-scope="{row}">
            <div class="actions-columns">
              <el-button type="text" size="small" @click="handelEdit(row)"> 修改</el-button>
              <el-button type="text" size="small" @click="handelDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" :page.sync="pages.page" :limit.sync="pages.limit" @pagination="changePages" />
    </div>
    <!-- 修改/新增弹窗 -->
    <el-dialog :title="isEdit ? '修改' : '新增'" :visible.sync="editVisible" width="900px">
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-form ref="ruleForm" :model="ruleForm" label-width="120px" class="demo-ruleForm">
          <el-form-item 
            label="白名单名称"
            prop="whitelistName"
            :rules="[
              { required: true, message: '请输入白名单名称', trigger: 'blur' },
              { required: true, message: '请输入白名单名称', trigger: 'change' }
            ]">
            <el-input v-model="ruleForm.whitelistName" />
          </el-form-item>
          <el-form-item label="白名单对象"
            prop="whiteTarget"
            :rules="[
              { required: true, message: '请选择白名单对象', trigger: 'blur' },
              { type: 'array', message: '请选择白名单对象', trigger: 'change' }
            ]"
          >
            <el-select v-model="ruleForm.whiteTarget"
              multiple
              clearable
              collapse-tags
              virtual-scroll
              ref="select"
              @change="setSelectedDealer"
              @clear="cleraSelect"
              @remove-tag="setDealers"
              style="width: 100%;" placeholder="请选择白名单对象">
               <el-option value="1" style="display: none;"></el-option>
               <white-target-select :provinves="allProvince" :cities="cityOptions" :dealeres="dealerOptions" @select="setSeleted" ref="whiteTargetSelect"/>
            </el-select>
            <div v-show="ruleForm.whiteTarget && ruleForm.whiteTarget.length" class="tips">
              已选择：<span v-for="item in ruleForm.whiteTarget" :key="item">{{ item }}、</span>
            </div>
          </el-form-item>
          <el-form-item 
            label="白名单城市"
            prop="city"
            :rules="[
              { required: true, message: '请选择白名单城市', trigger: 'blur' },
              { type: 'array', message: '请选择白名单城市', trigger: 'change' }
            ]"
          >
            <el-select v-model="ruleForm.city" multiple clearable filterable style="width: 100%;" placeholder="请选择白名单城市">
              <el-option v-for="(item, index) in cityOptions" :key="index + '_'+ item.cityCode" :label="item.cityName" :value="item.cityCode" />
            </el-select>
            <div v-show="ruleForm.city && ruleForm.city.length" class="tips">已选择：{{seletedCity}}</div>
          </el-form-item>
          <div class="effectiveTime">
            <el-form-item
              v-if="!effectiveEndTimeType"
              label="有效时间"
              prop="effectiveEndTime"
              :rules="[
                { required: true, message: '请选择有效时间', trigger: 'change' },
                { type: 'array', message: '请选择有效时间', trigger: 'change' }
              ]"
            >
                <el-date-picker 
                  type="daterange"
                  v-model="ruleForm.effectiveEndTime"
                  @change="setEffectiveEndTime"
                  clearable
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期" />
            </el-form-item>
            <el-form-item
              v-else
              label="有效时间"
            >
                <el-date-picker 
                  type="daterange"
                  v-model="ruleForm.effectiveEndTime"
                  @change="setEffectiveEndTime"
                  clearable
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期" />
            </el-form-item>
            <el-form-item>
              <el-radio @change="setEffectiveEndTimeRadio" v-model="effectiveEndTimeType" :label="1">永久有效</el-radio>
            </el-form-item>
          </div>
          <el-form-item
            label="备注"
          >
            <el-input
              v-model="ruleForm.remark"
              maxlength="200"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 5 }"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <div class="footer-action-button">
          <el-button type="primary" :loading="uploadLoading" @click="comfirmUpdate('ruleForm')">确 认</el-button>
          <el-button @click="editVisible = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryWhiteListDealer, deleteWhiteListDealer, switchWhiteListDealer, queryDealerList, addWhiteListDealer, editWhiteListDealer } from '@/api/crossRegionalMonitoring'
import Pagination from '@/components/Pagination'
import whiteTargetSelect from './whiteTargetSelect'
import { getStorageByKey, unique_arr_by_key, dateFtt, fomatComfirmStr } from '@/utils/public'
export default {
  name: 'RealTimeAlarm',
  components: { Pagination, whiteTargetSelect },
  data() {
    return {
      tables: {
        columns: [
          { lable: '白名单名称', key: 'whitelistName', align: 'center' },
          { lable: '白名单对象', key: 'dealerList', width: '240px', align: 'center' },
          { lable: '白名单城市', key: 'cityList', width: '240px', align: 'center' },
          { lable: '有效时间', key: 'endTime', width: '260px', align: 'center' },
          { lable: '创建时间', key: 'updateTime', width: '140px', align: 'center' },
          { lable: '备注', key: 'remark',  align: 'center' },
          { lable: '状态', key: 'status', width: '80px', align: 'center' }
        ],
        data: []
      },
      pages: {
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      dealerOptions: [],
      cityOptions: [],
      listLoading: true,
      editVisible: false,
      uploadLoading: false,
      simpleForm: {},
      effectiveEndTimeType: 0,
      ruleForm: {
        effectiveEndTime: null,
        city: null,
        whiteTarget: null,
        remark: '',
        whitelistName: ''
      },
      allProvince: [],
      checkedCities: [],
      isEdit: false
    }
  },
   filters: {
    listFomat(value) {
      const resutl = value.map(item => (
        item.name
      ))
      return resutl.join('、')
    },
    // 有效时间
    effectiveEndTimeFilter(row) {
      const { startTime, endTime, createTime } = row
      let effectiveEndTimeStr = ''
      if (startTime && endTime) {
        effectiveEndTimeStr = `${startTime}至${endTime}`
      } else if (startTime && !endTime) {
        effectiveEndTimeStr = `${startTime}至永久`
      } else if (!startTime && endTime) {
        effectiveEndTimeStr = `${createTime}至${endTime}`
      } else {
        effectiveEndTimeStr = '永久有效'
      }
      return effectiveEndTimeStr
    }
  },
  computed: {
    seletedCity() {
      const cities = this.ruleForm.city
      if (cities && cities.length) {
         const seleted = []
          this.cityOptions.forEach(item => {
            if(cities.includes(item.cityCode)) {
              seleted.push(item.cityName)
            }
          })
          return seleted.join('、')
      }else {
        return ''
      }
    }
  },
  created() {
    this.initData()
    this.queryTableList()
  },
  methods: {
    // 初始化相关数据
    initData() {
        this.cityOptions = this.initCityData()
        this.queryDealerList()
    },
    // 获取城市数据
    initCityData() {
       const regions = getStorageByKey('regionsMap')
       if (regions && regions.length) {
        const allProvince = regions.reduce((newArr, current) => {
            return newArr.concat(current.provinceList)
            }, [])
        this.allProvince = allProvince
        const allCity = allProvince.reduce((newArr, current) => {
            return newArr.concat(current.cityDtoList)
        }, [])
        return unique_arr_by_key('cityCode', allCity)
       } else {
            return []
       }
    },
    // 获取4s店列表
    async queryDealerList() {
      const { data } = await queryDealerList()
      const items = data
      this.dealerOptions = items
    },
    // 点击新增
    handelAdd() {
      this.editVisible = true
      this.isEdit = false
      this.ruleForm = {
        effectiveEndTime: null,
        city: [],
        whiteTarget: [],
        remark: '',
        whitelistName: ''
      },
      this.$refs.whiteTargetSelect.reset()
    },
    // 清除已选择的经销店
    cleraSelect() {
      this.$refs.whiteTargetSelect.reset()
      this.$forceUpdate()
    },
    // 移除已选择的单个tag
    setDealers(val) {
       const currentItem = this.dealerOptions.find(item => item.dealerName === val)
       const { dealerName, dealerCode } = currentItem
       this.$refs.whiteTargetSelect.setSelectDealer({ dealerName, dealerCode })
       this.$forceUpdate()
    },
    changePages(params) {
      this.pages = { ...params }
      this.queryTableList()
    },
    setEffectiveEndTime(val) {
      if (val) {
        this.effectiveEndTimeType = 0
      }
      this.$forceUpdate()
    },
    setEffectiveEndTimeRadio(val) {
      if (val) {
        this.ruleForm.effectiveEndTime = null
      }
      this.$forceUpdate()
    },
    async queryTableList() {
      this.listLoading = true
      const { data } = await queryWhiteListDealer(this.formatParams())
      const items = data
      if (items.list && items.list.length) {
        items.list.forEach(element => {
          const deaLerstr = element.dealerList.map(d => (d.name))
          const citystr = element.cityList.map(d => (d.name))
          element.dealerListStr = deaLerstr.join('、')
          element.cityListStr = citystr.join('、')
        })
      }
      this.tables.data = items.list
      this.total = items.total
      this.listLoading = false
    },
    formatAddParams() {
      const { whitelistName, dealerList, remark, effectiveEndTime, city } = this.ruleForm
      const params = {
        remark,
        whitelistName,
        dealerList,
        cityList: [],
        status: 0,
        startTime: '',
        endTime: ''
      }
      if (effectiveEndTime && effectiveEndTime.length) {
        params.startTime = dateFtt(effectiveEndTime[0])
        params.endTime = dateFtt(effectiveEndTime[1], 'yyyy-MM-dd') + ' 23:59:59'
      }
      this.cityOptions.forEach(item => {
        if(city.includes(item.cityCode)) {
          params.cityList.push({
            name: item.cityName,
            code: item.cityCode
          })
        }
      })
      params.dealerList = params.dealerList.map(item => ({
        name: item.dealerName,
        code: item.dealerCode
      }))
      return params
    },
    comfirmUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.uploadLoading = true
          const params = this.formatAddParams()
          if (!this.isEdit) {
            addWhiteListDealer(params).then(res => {
              this.editVisible = false
              this.queryTableList()
            }).finally(() => {
              this.uploadLoading = false
            })
          } else {
            editWhiteListDealer({...params, id: this.currentId}).then(res => {
              this.editVisible = false
              this.queryTableList()
            }).finally(() => {
              this.uploadLoading = false
            })
          }
         
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    formatParams() {
      const params = { ...this.simpleForm, ...this.pages }
      return params
    },
    // 清空查询条件
    handelRest() {
      for (const key in this.simpleForm) {
        this.simpleForm[key] = null
      }
    },
    // 启用/禁用
    toggleStatus(row) {
      const { startTime, endTime, createTime, id, status } = row
      const params = { id, status: status ? 0 : 1 }
      const confirmStr = fomatComfirmStr(startTime, endTime, createTime, status)
      this.$confirm(confirmStr, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        switchWhiteListDealer(params).then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.queryTableList()
        })
      }).catch(() => {
        row.status = status ? 0 : 1   
      });
    },
    handelEdit(row) {
      this.isEdit = true
      this.editVisible = true
      // console.log(this.$refs.ruleForm)
      // this.$refs.ruleForm.resetFields()
      const { whitelistName, cityList, dealerList, startTime, endTime, remark, status, id } = row
      this.currentId = id
      
      this.ruleForm.city = cityList.map(item => (item.code))
      this.ruleForm.whitelistName = whitelistName
      this.ruleForm.remark = remark
      this.ruleForm.status = status
      this.ruleForm.id = id
      this.ruleForm.effectiveEndTime = startTime ? [new Date(startTime), new Date(endTime)] : null
   
      const whiteTarget = [], dealer = []
      dealerList.forEach(item => {
        whiteTarget.push(item.name)
        dealer.push({
          dealerName: item.name,
          dealerCode: item.code
        })
      })
      this.ruleForm.dealerList = dealer
      this.ruleForm.whiteTarget = whiteTarget
      this.effectiveEndTimeType = startTime ? 0 : 1
      this.$refs.whiteTargetSelect.setEditDealer(dealer)
      this.$forceUpdate()
    },
    handelDelete(row) {
      const { id } = row
      this.$confirm('此操作将删除该经销店白名单，您确认要继续吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteWhiteListDealer(id).then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.queryTableList()
        })
      })
    },
    setSelectedDealer() {
      this.$forceUpdate()
      return false
    },
    setSeleted(value) {
      const seletedResult = value.map(item => (
        item.dealerName
      ))
      this.ruleForm.dealerList = value
      this.ruleForm.whiteTarget = seletedResult
      this.$nextTick((
        this.$forceUpdate()
      ))
    },
  }
}
</script>
<style scoped>
.workorder-problem-desc {
  background-color: #303133;
  color: #fff;
  border-color: #303133;
}
::v-deep .el-dialog__body{
  padding: 0px;
}
::v-deep .el-dialog__body{
    padding: 0px;
  }
</style>
<style lang="scss" scoped>
 .effectiveTime{
   width: 100%;
   display: flex;
 }
 .tips{
    color: #05a7ab;
    display: -webkit-box;
    font-size: 12px;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    max-height: 50px; /* 设置为行高的两倍 */
    line-height: 25px; /* 这里的行高应与下面p标签中的行高一致 */
    text-align: left;
  }
 .footer-action-button{
    margin-top: 80px;
 }
</style>
